<?php
/**
 * Created by xiaokengge
 * User: zhaoyu
 * Date: 2024/1/19
 * Time: 22:22
 *describe:****
 */

namespace app\api\service;


use EasyWeChat\Factory;

class OfficialAccountService
{
    protected $config = [
        'app_id' => 'wx56237a44263fb136',
        'secret' => '99711b4070c458c6804005a84b56a5b8',
        'verify' => false,
        // 下面为可选项
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',

//        'log' => [
//            'level' => 'debug',
//            'file' => __DIR__.'/wechat.log',
//        ],
    ];

    public $app;

    public function __construct()
    {
//        (new ThrowNewErr())->validateFailException('异常');
        $app = Factory::officialAccount($this->config);
        $this->app = $app;
    }

    public function getAccessToken()
    {

        // 获取 access token 实例
        $accessToken = $this->app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
//        $token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token.
        return $token;
    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    private function httpPost($url, $post_data = '', $timeout = 5)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        if ($post_data != '') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $file_contents = curl_exec($ch);
        curl_close($ch);

        return $file_contents;
    }


    /**
     * 从微信获取手机号
     * @param $code
     * @return string
     * @author: zhaoyu
     * @Time: 2024/1/19 23:04
     */
    public function getPhoneNumber($code)
    {
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $accessToken['access_token'];
        $app = Factory::miniProgram($this->config);
        $response = $app->httpPostJson($url, [
            'code' => $code,
        ]);
        $phone = '';
        if (isset($response['phone_info']) && !empty($response['phone_info'])) {
            $phone = $response['phone_info']['purePhoneNumber'];
        } else {
            (new ThrowNewErr())->validateFailException($response['errmsg']);
        }

        return $phone;

    }


}
